package com.runmi.webchat.aftersale.web.setup.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.common.utils.BaseExcelUtil;
import com.runmi.webchat.aftersale.common.utils.MD5;
import com.runmi.webchat.aftersale.common.utils.NumberUtil;
import com.runmi.webchat.aftersale.common.utils.StringUtil;
import com.runmi.webchat.aftersale.dbcore.dao.SetupItemDao;
import com.runmi.webchat.aftersale.dbcore.dao.ShopInfoDao;
import com.runmi.webchat.aftersale.dbcore.entity.Role;
import com.runmi.webchat.aftersale.dbcore.entity.SetupItem;
import com.runmi.webchat.aftersale.dbcore.entity.ShopInfo;
import com.runmi.webchat.aftersale.dbcore.entity.User;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupItemMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupOrderMapper;
import com.runmi.webchat.aftersale.util.Constants;
import com.runmi.webchat.aftersale.web.base.BaseService;
import com.runmi.webchat.aftersale.web.set.model.UserEdit;
import com.runmi.webchat.aftersale.web.setup.vo.SetupItemEdit;
import com.runmi.webchat.aftersale.web.setup.vo.SetupItemImportTemp;
import com.runmi.webchat.aftersale.web.setup.vo.SetupItemReqVo;

@Service
public class SetupItemService extends BaseService{

	@Autowired
	private  SetupItemMapper setupItemMapper;
	
	@Autowired
	private ShopInfoDao shopInfoDao;
	
	@Autowired
	private SetupItemDao setupItemDao;
	
	public void index(SetupItemReqVo model){
		 try{		
			 
			    model.setShopInfos(shopInfoDao.getAllShopInfoList());		 
			    PageHelper.startPage(model.getCpage(), model.getPageSize());
				List<Map> items=setupItemMapper.queryItemByCondition(
						model.getShopId(),
						model.getItemCode(), model.getItemName(),
						model.getBarCode(),model.getEmail(), model.getStatus());
				PageInfo<Map> pageInfo = new PageInfo<Map>(items);
				model.setTotalCount((int)pageInfo.getTotal());
				
				 for(Map item:items){
		            	Long salePrice=null==item.get("sale_price")?null:Long.parseLong(item.get("sale_price").toString());
		            	item.put("price",NumberUtil.forPriceView(salePrice));
		            	
		            }
				
				
				model.setItems(items);
			}catch(Exception ex){
				ex.printStackTrace();
				
			}
	}
	
	public Map<String,String> changeStatus(User erpUser, Integer id,Byte opType){
		Map<String,String> result=new HashMap<String,String>();
		try{
			this.log.info("用户" + erpUser.getRealName() + " 操作:" + id + " 操作类型:" + opType );
			if(id==null || null==opType){
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, "数据异常");					
				return result;
			}
			SetupItem model= setupItemMapper.selectByPrimaryKey(id);
			if(null==model){
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, "未查询到数据");					
				return result;
			}
			if(opType.intValue()==1){
				SetupItem record=new SetupItem();
				record.setId(id);
				//record.setUpdateTime(new Date());
				record.setStatus((byte)2);							
				setupItemMapper.updateByPrimaryKeySelective(record);
			}
			if(opType.intValue()==2){
				//冻结
				SetupItem record=new SetupItem();
				record.setId(id);
				//record.setUpdateTime(new Date());
				record.setStatus((byte)1);							
				setupItemMapper.updateByPrimaryKeySelective(record);
			}	
			result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
			result.put(Constants.RETURN_MESSAGE_KEY, "success");		
			
			
		}catch(Exception ex){
			ex.printStackTrace();
			result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
			result.put(Constants.RETURN_MESSAGE_KEY, ex.getMessage());	
		}
		return result;
	}
	public Result del(User user, Integer id){
		Result result= ResultFactory.getResultFail();
		try{
			this.log.info("用户" + user.getRealName() + "  del user:" + id );
			if(id==null){
//				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
//				result.put(Constants.RETURN_MESSAGE_KEY, "数据异常");		
				result=ResultFactory.getResultFail("数据异常");
				return result;
			}
			SetupItem model= setupItemMapper.selectByPrimaryKey(id);
			if(null==model){	
				result=ResultFactory.getResultFail("未查询到数据");
				return result;
			}
			
			SetupItem record=new SetupItem();
			record.setId(model.getId());
			//record.setUpdateTime(new Date());
			record.setDelFlag((byte)1);		
			
			setupItemMapper.updateByPrimaryKeySelective(record);
			
			result=	ResultFactory.getResultSuccess();
			
			
		}catch(Exception ex){
			ex.printStackTrace();
			result=ResultFactory.getResultFail(ex.getMessage());
//			result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
//			result.put(Constants.RETURN_MESSAGE_KEY, ex.getMessage());	
		}
		return result;
	}
	
	
	public void edit(SetupItemEdit model){	
		 model.setShopInfos(shopInfoDao.getAllShopInfoList());	
		SetupItem item= setupItemMapper.selectByPrimaryKey(model.getItemId());
		item=item==null?new SetupItem():item;
		model.setPrice(NumberUtil.forPriceView(item.getSalePrice()));
		model.setSetupItem(item);
		
	}
	public Map<String,String> save(SetupItemEdit model){
		Map<String,String> result=new HashMap<String,String>();
		if(model.getIsSetupPrice()==null){
			model.setIsSetupPrice((byte)0);
		}
		if(null!=model.getItemId()){
			SetupItem itemModel= setupItemMapper.selectByPrimaryKey(model.getItemId());
			if(null!=itemModel){				
				SetupItem record=new SetupItem();
				record.setShopId(model.getShopId());
				record.setId(itemModel.getId());
				record.setItemCode(model.getItemCode());
				record.setItemName(model.getItemName());
				record.setBarCode(model.getBarCode());
				record.setEmail(model.getEmail());	
				record.setIsSetupPrice(model.getIsSetupPrice());
				if(null!=model.getIsSetupPrice() && model.getIsSetupPrice().equals((byte)1)){
					record.setSetupPrice(model.getSetupPrice());
				}
				record.setItemType(model.getItemType());
				record.setDeliveryType(model.getDeliveryType());
				record.setItemUrl(model.getItemUrl());
				record.setItemDesc(model.getItemDesc());
				if(model.getSalePrice() != null){
					record.setSalePrice((long)(model.getSalePrice()*100));
				}
			
				setupItemMapper.updateByPrimaryKeySelective(record);
			}else{
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, "未查询到用户");					
				return result;
			}
		}else{
			SetupItem record=new SetupItem();
			record.setShopId(model.getShopId());
			record.setItemCode(model.getItemCode());
			record.setItemName(model.getItemName());
			record.setBarCode(model.getBarCode());
			record.setEmail(model.getEmail());	
			record.setIsSetupPrice(model.getIsSetupPrice());
			if(null!=model.getIsSetupPrice() && model.getIsSetupPrice().equals((byte)1)){
				record.setSetupPrice(model.getSetupPrice());
			}
			if(model.getSalePrice() != null){
				record.setSalePrice((long)(model.getSalePrice()*100));
			}
			record.setItemType(model.getItemType());
			record.setDeliveryType(model.getDeliveryType());
			record.setItemUrl(model.getItemUrl());
			record.setItemDesc(model.getItemDesc());
			record.setCreateTime(new Date());
			record.setDelFlag((byte)0);
			record.setEmail(model.getEmail());
			record.setStatus((byte)1);				
			setupItemMapper.insert(record);
		
		}
		result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
		result.put(Constants.RETURN_MESSAGE_KEY, "success");	
		return result;
	}
	
	
	public Result importfile(MultipartFile file) {
		List<SetupItemImportTemp> createImportTempList = new ArrayList<SetupItemImportTemp>();
		try {
			String fileName = file.getOriginalFilename();
			if (StringUtil.isBlank(fileName)) {
				return ResultFactory.getResultFail("文件错误");
			}
			if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
				return ResultFactory.getResultFail("文件格式错误");
			}

			Workbook workbook = BaseExcelUtil.getWorkBook(file);
			if (workbook != null) {
				Sheet sheet = workbook.getSheetAt(0);
				if (sheet == null) {
					return ResultFactory.getResultFail("文件导入格式sheet错误");
				}

				//获得当前sheet的开始行
				int firstRowNum = sheet.getFirstRowNum();
				//获得当前sheet的结束行
				int lastRowNum = sheet.getLastRowNum();
				//循环除了第一行的所有行
				for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
					Row row = sheet.getRow(rowNum);
					int nowRow = rowNum + 1;
					if (row == null) {
						continue;
					}

					SetupItemImportTemp createImportTemp = new SetupItemImportTemp();
					Cell cell0 = row.getCell(0);

					String shopCode = BaseExcelUtil.getCellValue(cell0);
					if (StringUtil.isBlank(shopCode)) {
						String error = String.format("第%s行门店编码错误", nowRow);
						return ResultFactory.getResultFail(error);
					}
					ShopInfo shopInfo=this.shopInfoDao.getShopInfoByCode(shopCode);
					if(null==shopInfo){
						String error = String.format("第%s行店铺编码未查找到", nowRow);
						return ResultFactory.getResultFail(error);
					}
					createImportTemp.setShopInfo(shopInfo);
					createImportTemp.setShopCode(shopCode);

					
					
					Cell cell2 = row.getCell(2);
					String itemCode = BaseExcelUtil.getCellValue(cell2).trim();
					if (StringUtil.isBlank(itemCode)) {
						String error = String.format("第%s行商品编码未录入", nowRow);
						return ResultFactory.getResultFail(error);
					}
					createImportTemp.setItemCode(itemCode);
					
					Cell cell3 = row.getCell(3);
					String itemName = BaseExcelUtil.getCellValue(cell3).trim();
					if (StringUtil.isBlank(itemName)) {
						String error = String.format("第%s行SKU名称未录入", nowRow);
						return ResultFactory.getResultFail(error);
					}
					createImportTemp.setItemName(itemName);
					
				
													
					Cell cell4 = row.getCell(4);
					String barCode = BaseExcelUtil.getCellValue(cell4).trim();
					if (StringUtil.isBlank(barCode)) {
						String error = String.format("第%s行69码未录入", nowRow);
						return ResultFactory.getResultFail(error);
					}
					createImportTemp.setBarCode(barCode);
					
						
					Long salePrice=0L;
				
					Cell cell5 = row.getCell(5);
					String salePriceStr = BaseExcelUtil.getCellValue(cell5).trim();
					if (StringUtil.isNotEmptyStr(salePriceStr)) {
						try{
							Double k=Double.parseDouble(salePriceStr);
							salePrice=(long) (k*100);
						}catch(Exception ex){
							ex.printStackTrace();
							String error = String.format("第%s行价格转换错误", nowRow);
							return ResultFactory.getResultFail(error);
						}
					}else{
						//salePrice=itemInfo.getSalePrice();//带销售价
					}
					createImportTemp.setSalePrice(salePrice);
					
					Cell cell6 = row.getCell(6);
					String setPrice = BaseExcelUtil.getCellValue(cell6).trim();
					if(setPrice.equals("") || setPrice.equals("否")){
						createImportTemp.setIsSetupPrice((byte)0);
					}else{
						createImportTemp.setIsSetupPrice((byte)1);
					}
					if(null!=createImportTemp.getIsSetupPrice() && createImportTemp.getIsSetupPrice().equals((byte)1)){
						//record.setSetupPrice(model.getSetupPrice());
						Cell cell7 = row.getCell(7);
						String setupPrice = BaseExcelUtil.getCellValue(cell7).trim();
						if(StringUtil.isBlank(setupPrice)){
							String error = String.format("第%s行安装费用必须录入", nowRow);
							return ResultFactory.getResultFail(error);
						}
						createImportTemp.setSetupPrice(setupPrice);
					}
					
				
					
					Cell cell8 = row.getCell(8);
					String qty = BaseExcelUtil.getCellValue(cell8).trim();
					if(!qty.equals("") && qty.equals("管库存")){
						createImportTemp.setItemType((byte)1);
					}else{
						createImportTemp.setItemType((byte)0);
					}
				//	 '1:门店发货 2仓库配送 3供应商发货',
								
					Cell cell9 = row.getCell(9);
					String attr = BaseExcelUtil.getCellValue(cell9).trim();					
					if(attr.equals("门店发货")){
						createImportTemp.setDeliveryType((byte)1);
					}
					if(attr.equals("仓库配送")){
						createImportTemp.setDeliveryType((byte)2);
					}
					if(attr.equals("供应商发货")){
						createImportTemp.setDeliveryType((byte)3);
					}
					

					Cell cell10 = row.getCell(10);
					String email = BaseExcelUtil.getCellValue(cell10).trim();
					createImportTemp.setEmail(email);
					
					Cell cell11 = row.getCell(11);
					String vo = BaseExcelUtil.getCellValue(cell11).trim();
					createImportTemp.setItemUrl("/img/"+ vo);
					
											
				
					createImportTempList.add(createImportTemp);
				}

				if (createImportTempList.size() > 0) {
					return ResultFactory.getResultListSuccess(createImportTempList);
				} else {
					return ResultFactory.getResultFail("未导入任何数据");
				}
			} else {
				return ResultFactory.getResultFail("文件导入格式错误");
			}
		} catch (Exception e) {
			logErr.error("解析导入生产订单异常", e);
			return ResultFactory.getResultFail("解析导入生产订单异常");
		}
	}
    @Transactional
	public void insertDbFromImportFile(List<SetupItemImportTemp> createImportTempList, User user) throws Exception {
		try {
			
			for(SetupItemImportTemp item:createImportTempList){
				SetupItem setupItem= setupItemDao.getItemByShopAndItemCode(item.getShopInfo().getId(), item.getItemCode());
				if(null!=setupItem){
					setupItem.setBarCode(item.getBarCode());
					setupItem.setDeliveryType(item.getDeliveryType());
					setupItem.setEmail(item.getEmail());
					setupItem.setIsSetupPrice(item.getIsSetupPrice());
					setupItem.setSetupPrice(item.getSetupPrice());
					setupItem.setItemCode(item.getItemCode());
					setupItem.setItemDesc(item.getItemDesc());
					setupItem.setItemName(item.getItemName());
					setupItem.setItemType(item.getItemType());
					setupItem.setItemUrl(item.getItemUrl());
					setupItem.setSalePrice(item.getSalePrice());
					setupItem.setShopId(item.getShopInfo().getId());
					setupItemMapper.updateByPrimaryKey(setupItem);
				}else{
					//setupItemMapper
					setupItem=new SetupItem();
					setupItem.setBarCode(item.getBarCode());
					setupItem.setDeliveryType(item.getDeliveryType());
					setupItem.setEmail(item.getEmail());
					setupItem.setIsSetupPrice(item.getIsSetupPrice());
					setupItem.setSetupPrice(item.getSetupPrice());
					setupItem.setItemCode(item.getItemCode());
					setupItem.setItemDesc(item.getItemDesc());
					setupItem.setItemName(item.getItemName());
					setupItem.setItemType(item.getItemType());
					setupItem.setItemUrl(item.getItemUrl());
					setupItem.setSalePrice(item.getSalePrice());
					setupItem.setShopId(item.getShopInfo().getId());
					setupItem.setCreateTime(new Date());
					setupItem.setStatus((byte)1);
					setupItem.setDelFlag((byte)0);
					setupItemMapper.insert(setupItem);
				}
			}

			
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error("将导入的文件数据插入到数据库中", e);
			throw new Exception("将导入的文件数据插入到数据库中", e);
		}
	}
	
	
}
